<template>
    <a-select :show-search="showSearch" v-model="myValue" placeholder="请选择" @change="selectChange" :placeholder="placeholder"
        @search="search" :filter-option="filterOption">
        <a-select-option :value="val?item[val]:item" v-for="item in list" :key="item[val]"
            :disabled="!!item.isDel || (item===defName && hideMine)">{{name?item[name]:item}}{{name2?('_'+item[name2]):''}}</a-select-option>
    </a-select>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch, Model } from "vue-property-decorator";
@Component({
    name: "yuanSelect",
    components: {},
})
export default class extends Vue {
    @Prop({ default: [] }) list!: any[];
    @Prop({ default: "" }) val!: string;
    @Prop({ default: "" }) name!: string;
    @Prop({ default: "" }) name2!: string;
    @Prop({ default: "" }) placeholder!: string;
    @Prop({ default: "" }) defName!: string;
    @Prop({ default: false }) showSearch!: boolean;

    @Model("input", { default: "" }) value!: any;

    myValue: any = "";
    hideMine = false;
    @Watch("value")
    valueChange(newVal: string) {
        this.myValue = newVal;
        this.getDefOne();
    }
    @Watch("list")
    listChange(newVal: string) {
        this.getDefOne();
    }
    @Watch("defName")
    defNameChange(newVal: string) {
        this.getDefOne();
    }
    selectChange(e: any) {
        this.$emit("input", e);
        this.$emit("change", e);
    }
    search(e: any) {
        this.$emit("search", e);
    }
    filterOption(input, option) {
        return (
            option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
    }
    doTime: number | null = null;
    getDefOne() {
        if(this.doTime) clearTimeout(this.doTime)
        this.doTime = setTimeout(() => {
            try {
                if (this.val && this.name) {
                    const find = this.list.find((item) => item[this.val] === this.value);
                    if (find) return;
                    if (!this.value || !this.defName) return;
                    const one: any = {};

                    one[this.val] = this.value;
                    one[this.name] = this.defName;
                    one.isDel = true;
                    this.list.push(one);
                } else {
                    const find = this.list.find((item) => item === this.defName);
                    if (find) return;
                    if (!this.value || !this.defName) return;
                    this.list.push(this.defName);
                    this.hideMine = true;
                }
            } catch (error) {
                //
            }
        }, 100);
    }
    mounted() {
        this.myValue = this.value ? this.value + "" : undefined;
        this.getDefOne();
    }
}
</script>

<style>
</style>
